<template>
  <div class="container">
    <!-- 新增学科弹窗 -->
    <el-dialog
      title="新增学科"
      :visible="addDialogVisible"
      @close="closeDialog"
      width="50%"
    >
      <!-- 主体区域 -->
      <el-row>
        <el-col>
          <el-form
            :model="addSubjectsFrom"
            :rules="addSubjectsFromRules"
            ref="addSubjectsFromRef"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="学科名称" prop="subjectName">
              <el-input
                v-model="addSubjectsFrom.subjectName"
                placeholder="请输入学科名称"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <span class="subspan">是否显示</span>
        <el-switch
          v-model="SubSwitchValue"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-row>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('close-dialog')">取 消</el-button>
        <el-button type="primary" @click="addSubFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Subject from '../../api/hmmm/subjects'
export default {
  props: {
    addDialogVisible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      // 添加学科是否显示的开关
      SubSwitchValue: true,
      // 添加的输入框数据
      addSubjectsFrom: {
        subjectName: ''
      },
      // 添加的验证
      addSubjectsFromRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isFrontDisplay () {
      if (this.SubSwitchValue) {
        return 1
      } else {
        return 0
      }
    }
  },
  methods: {
    closeDialog () {
      this.$emit('close-dialog')
      // 重置表单内容
      this.$refs.addSubjectsFromRef.resetFields()
      // 手动清空是否显示的字段
      this.SubSwitchValue = ''
    },
    // 添加学科
    async addSubFrom () {
      try {
        await Subject.add({
          subjectName: this.addSubjectsFrom.subjectName,
          isFrontDisplay: this.isFrontDisplay
        })
        // 提示用户
        this.$message.success('新增学科成功')
        // 关闭弹窗
        this.$emit('close-dialog')
        // 刷新表格数据
        this.$emit('get-subjects-list')
      } catch (e) {
        this.$message.error('新增学科失败')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  .subspan {
    font-size: 14px;
    font-weight: 700;
    margin-right: 10px;
    margin-left: 10px;
  }
}
</style>
